﻿using System.Globalization;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using NHibernate.Sidekick.Utils.Extensions;

namespace NHibernate.Sidekick.Utils.MappingConventions
{
    /// <summary>
    /// Sets the foreign key names with the convention "FK_{FirstTable}_{SecondTable}".
    /// </summary>
    public class ForeignKeyConstraintConvention : IHasManyConvention
    {
        /// <summary>
        /// Apply changes to the target.
        /// </summary>
        /// <param name="instance"></param>
        public void Apply(IOneToManyCollectionInstance instance)
        {
            var keyName = string.Format(CultureInfo.InvariantCulture, "FK_{0}_{1}",
                                        instance.Member.Name,
                                        instance.EntityType.Name).Truncate(30);

            instance.Key.ForeignKey(keyName);
        }
    }
}